package com.cynteka.cyfoman.core.collection;

import com.cynteka.cyfoman.core.IValueObject;
import com.cynteka.cyfoman.core.ValueObject;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

/**
 * User: Sergey
 * Date: 29.07.11
 * Time: 17:37
 */
public class ValueObjectRowMapper<ID> implements RowMapper<IValueObject<ID, String>> {
    private final String fieldId;

    public ValueObjectRowMapper(String fieldId) {
        this.fieldId = fieldId;
    }

    @Override
    public IValueObject<ID, String> mapRow(ResultSet resultSet, int rowIdx) throws SQLException {

        ResultSetMetaData md = resultSet.getMetaData();
        ValueObject<ID, String> res = new ValueObject<ID, String>();
        for (int i = 0; i < md.getColumnCount(); i++) {
            String columnName = md.getColumnName(i + 1);
            Object o = resultSet.getObject(i + 1);
            res.setParam(columnName, o);
        }
        res.setId((ID) resultSet.getObject(fieldId));
        return res;

    }
}
